#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/12/18 15:43
# @Author : 闫峰
# @File    : category_lose_service.py
import datetime
import json

import requests

from common.setting import ensure_path_sep
from utils.mysqlUtils.db_pool import Database
import os
import threading
import time
from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database
from utils.mysqlUtils.mongodb_utils import MongoDBLink

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])


def remove_file(info_path):
    if os.path.exists(info_path):
        os.remove(info_path)
    else:
        print(f"{info_path} 不存在")


info_path = ensure_path_sep(f"\\logs\\info-{dis_path}{time.time()}")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}{time.time()}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}{time.time()}.log")
remove_file(info_path)
remove_file(error_path)
remove_file(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')


class CategoryLose:
    znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")

    def category_lose(self):

        id_index = 0
        while True:
            get_category_list = """
            SELECT id,CategoryId
            FROM p_market_product 
            WHERE id> %s
            and MarketId=67
            order by id
            limit 500
            """
            INFO.logger.info(f"id_index={id_index}")

            category_list = self.znkd_db.fetch_all_tuple(get_category_list, (id_index,))
            if not len(category_list):
                break
            id_index = category_list[-1][0]
            # 过滤掉类目 = “”的数据
            category_list = list(filter(lambda x: x[1] != "", category_list))
            if not len(category_list):
                continue
            no_exist_categoty_set = self.get_no_exist_categoty_set(category_list)
            if not no_exist_categoty_set:
                continue
            # 去重为空的数据
            no_exist_categoty_set = set(filter(lambda x: x != "", no_exist_categoty_set))
            # 验证这个分类在 p_market_product 表  CategoryId字段不存在  CategoryId=CategoryId的数据
            check_p_market_product = """
            SELECT id
            FROM p_market_product
            WHERE MarketId=67
            AND CategoryId IN %s
            """
            res = self.znkd_db.fetch_all_tuple(check_p_market_product, (no_exist_categoty_set,))
            if res:
                print()
                continue
            # 验证 这个分类下的所有SKU属性数据删除 p_market_product_attribute

    def get_no_exist_categoty_set(self, category_list):
        category_set = set(map(lambda x: x[1], category_list))

        get_exist_categoty_list = """
        SELECT CategoryId
        FROM m_allegro_marketcategory
        WHERE MarketId=67
        AND SiteCode='PL'
        AND CategoryId in  %s
        and IsLeaf =1
        AND IsDelete=0
        """
        exist_categoty_list = self.znkd_db.fetch_all_tuple(get_exist_categoty_list, (category_set,))
        exist_categoty_set = set(map(lambda x: x[0], exist_categoty_list))

        return category_set - exist_categoty_set


if __name__ == '__main__':
    CategoryLose().category_lose()
